using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace XLFrame
{
    /// <summary>
    /// 利用Unity的JsonUtility对Unity对象进行序列化和反序列化
    /// </summary>
    public class UnityObjectConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(UnityEngine.Object).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject jObject = JObject.Load(reader);
            jObject["value"] = jObject;

            var jsonUnityObject = JsonUtility.FromJson<JsonUnityObject>(jObject.ToString());
            return jsonUnityObject.value;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            
            JsonUnityObject jsonObject = new JsonUnityObject((UnityEngine.Object)value);
            JObject jObject = new JObject
            {
                ["instanceID"] = new JValue(((UnityEngine.Object)value).GetInstanceID())
            };
            jObject.WriteTo(writer);
        }

        public class JsonUnityObject
        {
            public UnityEngine.Object value;

            public JsonUnityObject(UnityEngine.Object value)
            {
                this.value = value;
            }
        }
    }
}
